import axios from "axios";

const instance = axios.create({
  baseURL: "http://himapi.zs022.cn/",
});

instance.interceptors.request.use((config) => {
  return config;
});

instance.interceptors.response.use((response) => {
  return response.data?.data ? response.data.data : response.data;
});

export function post(url: string, data?: any) {
  return new Promise((resolve, reject) => {
    instance({
      method: "post",
      url,
      data: data,
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function downloadFile(url: string, data?: any, fileName?: string) {
  return new Promise((resolve, rejejct) => {
    instance({
      method: "post",
      url,
      data: data,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      responseType: "blob",
    }).then((res: any) => {
      const href = URL.createObjectURL(res);
      const link = document.createElement("a");
      link.download = fileName || "1.xlsx";
      link.href = href;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(href);
      resolve(1);
    });
  });
}

export function get(url: string, data?: any) {
  return new Promise((resolve, reject) => {
    instance({
      method: "get",
      url,
      params: data,
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
